package com.zhq.blog.manage.domain.fronted.controller;

import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zhq.blog.core.domain.user.User;
import com.zhq.blog.core.domain.user.UserRepository;

/**
 * @title:SessionUser.java
 * @package com.zhq.blog.manage.domain.fronted.controller
 * @author 张恒强
 * @date 2015年1月5日 上午9:54:43
 * @version V1.0
 */
@Service
public class SessionUser {
	
	@Autowired
	private UserRepository userRepository;
	
	private String id;

	public SessionUser getOrCreateSession(String sessionId){
		SessionUser session = new SessionUser();
		session.setUserRepository(userRepository);
		if(sessionId == null){
			session.id = UUID.randomUUID().toString();
		}else{
			session.id = sessionId;
		}
		return session;
	}


	public UserRepository getUserRepository() {
		return userRepository;
	}

	public void setUserRepository(UserRepository userRepository) {
		this.userRepository = userRepository;
	}


	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}
	
	public User user;


	public void setUser(HttpServletRequest request,User user) {
	}
	
	/**
	 * 得到当前会话的操作员，如果无法得到则返回null
	 * @return 得到当前会话的操作员，如果无法得到则返回null
	 */
	public User getUser(HttpServletRequest request) {
		long userId = getUserId(request);
		if(userId == 0){
			return null;
		}else{
			return userRepository.findOne(userId);
		}
		
	}
	
	private long getUserId(HttpServletRequest request) {
		if(request.getSession().getAttribute(id)!=null && !request.getSession().getAttribute(id).equals("")){
			return Long.parseLong(request.getSession().getAttribute(id).toString());
		}else{
			return 0;
		}
	}

}
